/**
 
 @Name: layuiSimpleNews - 极简新闻资讯模板
 @Author: star1029
 @Copyright
 
 */


layui.define(['element', 'form', 'laypage', 'upload', 'carousel'], function(exports){
  var $ = layui.$
  ,element = layui.element
  ,form = layui.form
  ,laypage = layui.laypage
  ,carousel = layui.carousel;

  //头部——点击切换
  var headNav = $(".news-header").find(".header-nav")
  $(".news-header").find("#switch").on('click', function(){
    if(headNav.hasClass("close")){
      $(".news-header").children(".layui-container").height(60 + headNav.height());
      headNav.removeClass("close");
    }else{
      $(".news-header").children(".layui-container").height(50);
      headNav.addClass("close");
    };
  });

  //头部——搜索框
  $(".news-header").find(".header-search").children("input").on('keydown', function(e){
    if(e.keyCode === 13){
      e.preventDefault();
      var _word=$.trim($("#searchword").val());
      if(_word==''){
    	  layer.msg("搜索关键词不能为空", {
   			  time: 1500 
 			});
    	  return false;
      }
      window.location.href = geturl('topic/search')+"?word="+_word;
    };
  });
  $(".btnattention").click(function(){
		var _uid=$(this).attr("data-uid");
		attentto_user(_uid);
	})
	window.login=function(){
	  window.location.href=geturl("user/login");
  }
	/*关注用户*/
function attentto_user(uid) {

  if (g_uid == 0) {
      login();
  }
  if(g_uid==uid){
  	layer.msg("不能关注自己");
  	return false;
  }
  $.post(geturl("user/attentto"), {uid: uid}, function(msg) {
  
      if (msg == 'ok') {
          if ($("#attenttouser_"+uid+",."+"attenttouser_"+uid).hasClass("following")) {
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).removeClass("following");
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).addClass("follow");                
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).html('关注');
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).attr('title','+关注');
          } else {
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).removeClass("follow");
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).addClass("following");         
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).html('已关注');
              $("#attenttouser_"+uid+",."+"attenttouser_"+uid).attr('title','已关注');
          }
         
      }
  });
}
$(".button_commentagree").click(function(){
    var supportobj = $(this);
            var tid = $(this).attr("id");
            $.ajax({
            type: "GET",
                    url:geturl("topic/ajaxhassupport/"+tid),
                    cache: false,
                    success: function(hassupport){
                    if (hassupport != '1'){






                            $.ajax({
                            type: "GET",
                                    cache:false,
                                    url: geturl("topic/ajaxaddsupport/"+tid),
                                    success: function(comments) {

                                    supportobj.find("em").html(comments);
                                    }
                            });
                    }else{
                   	 layer.msg("您已经赞过");
                    }
                    }
            });
    });
//发布文章评论
$(".btn-cm-submit").click(function(){
	postarticle();

    
});
function postarticle(){
	 ctrdown=false;
	 returndown=false;
	 var artcomment=$.trim($(".comment-area").val());
   var _tid=$("#artid").val();
   var _artitle=$("#artitle").val();
   
	var url=geturl("topic/ajaxpostcomment");
	if(artcomment==''){
		 layer.msg("评论不能为空")
	  
		return false;
	}
   $.ajax({
       //提交数据的类型 POST GET
       type:"POST",
       //提交的网址
       url:url,
       //提交的数据
      data:{title:_artitle,tid:_tid, content:artcomment},
       //返回数据的格式
       datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
       beforeSend: function () {
   
       },
       //成功返回之后调用的函数
       success:function(data){
         
            
           var  jsondata=eval('(' + data+ ')');
          
           layer.msg(jsondata.msg)
     
          
          if(jsondata.state==1){
       	   window.location.reload();
          }
          if(jsondata.state==-1){
       	   login();
          }
          
       }   ,
       complete: function () {
         
       },
      
       //调用出错执行的函数
       error: function(){
           //请求出错处理
       }
   });
}
  $("#login_submit").click(function(){
		 var _forward=$("#forward").val();
	    var _uname=$("#xm-login-user-name").val();
	    var _upwd=$("#xm-login-user-password").val();
	    var _apikey=$("#tokenkey").val();
	 
	    	var loading = null;
	    $.ajax({
	        //提交数据的类型 POST GET
	        type:"POST",
	        //提交的网址
	        url:geturl("api_user/loginapi") ,
	        //提交的数据
	        data:{uname:_uname,upwd:_upwd,apikey:_apikey},
	        //返回数据的格式
	        datatype: "text",//"xml", "html", "script", "json", "jsonp", "text".
	        beforeSend: function () {

	        	loading=layer.load(0, {
	                shade: false,
	                time: 2*1000
	            });
	         },
	        //成功返回之后调用的函数
	        success:function(data){
	        	data=$.trim(data);
				console.log(data)
			
						if(data.indexOf('ok|')>=0){
					var datastrs=data.split('|');
					$("body").append(datastrs);
					data='login_ok';
				}
	            if(data=='login_ok'){





	             	
	            	if(_forward.indexOf('user/getphonepass')>=0||_forward.indexOf('user/getpass')>=0||_forward.indexOf('user/logout')>=0||_forward.indexOf('user/checkemail')>=0){
	             		window.location.href=g_site_url;
	             	}else{
	             		window.location.href=_forward;
	             	}





	            }else{
	            	  switch(data){
	            	  case 'login_null':
	            		 layer.msg("用户名或者密码为空", {
	           			  time: 1500 
	         			});
	            		  break;
	 case 'login_user_or_pwd_error':
		 layer.msg("用户名或者密码错误", {
			  time: 1500 
			});
	            		  break;
	default:
		layer.msg(data, {
			  time: 1500 
			});
		break;
	            	  }
	            }
	        }   ,
	        complete: function () {
	        	layer.close(loading);
	         },
	        //调用出错执行的函数
	        error: function(){
	      	 layer.msg("请求异常", {
	 			  time: 1500 
			});
	            //请求出错处理
	        }
	    });
	});
  function geturl(_url){
		return g_site_url+g_prefix+_url+g_suffix;
	}
  //底部——微信、微博
  $(".news-footer").find("#wechat").hover(
    function(){ $(".news-footer").find("#code").fadeIn(); },
    function(){ $(".news-footer").find("#code").fadeOut(); }
  );
  $(".news-footer").find("#weibo").hover(
    function(){ $(".news-footer").find("#code").fadeIn(); },
    function(){ $(".news-footer").find("#code").fadeOut(); }
  );
  //初始化
  var scrChange = function(){
    var scr = $(document).scrollTop()
    ,height = document.body.offsetHeight - 140 + $(document).scrollTop();  
    if(document.body.clientWidth >= 751){
      $(".news-detail").find("#detail-handel").css("top", scr);
      $("#silde").css("top", height);
    }else{
      $(".news-detail").find("#detail-handel").css("top", 70);
      $("#silde").css("top", "auto");
    }
  }
  ,liAppend = function(){
    var navLi = $(".news-header").find(".header-nav").children(".more").find(".hida");
    if(document.body.clientWidth >= 751){
      $(".news-header").find(".header-nav").children("li").children(".hida").parent("li").remove();
    }else{
      if($(".news-header").find(".header-nav").children("li").children("a").hasClass("hida")){ }
      else{
        navLi.clone().appendTo( $(".news-header").find(".header-nav") ).wrap('<li class="layui-nav-item"></li>');
      }
    }
  };
  $(function(){
    scrChange();
    liAppend();
    $("#silde").children("#refresh").on('click', function(){
      window.location.reload();
    });
    $("#silde").children("#scroll").on('click', function(){
      $("html,body").animate({scrollTop: 0}, 500);
    });
    $(".news-user").find(".userCont").children(".layui-tab-content").find(".article").children("li").each(function(index){
       if(index%2 != 0){
        $(this).addClass("even");
       }
    });
  });
  //侧边栏固定
  $(window).resize(function(){   
    scrChange();
    liAppend();
  });
  window.onscroll = scrChange;
  //首页——轮播
  carousel.render({
    elem: '#newsIndex'
    ,width: '100%'
    ,height: '400px'
    ,arrow: 'none' 
  });
  //详情页——跳转评论
  $(".news-detail").find("#detail-handel").find(".review").on('click', function(){
    var height = $(".news-detail").find(".detail-comment").offset().top - 20;
    $('html,body').animate({scrollTop: height}, 800);
    $(".news-detail").find(".detail-comment").find("textarea").focus();
  });


  //详情页——回复点赞
  $(".news-detail").find("#replyCont").children("li").each(function(){
  
    $(this).find("a").filter(".reply").on('click', function(){
      var reply = $(this);
      reply.before('<div class="content"><textarea placeholder="写下您想说的评论吧..." class="layui-textarea"></textarea><div class="btn"><button class="layui-btn btn-revert">回复</button></div></div>')
      reply.parent(".readCom").find(".btn-revert").on('click', function(){
        $(this).parents(".content").remove();
        layer.msg('已回复！');
        reply.show();
      });
      reply.hide();
    });
  });
  //详情页——分页
  laypage.render({
    elem: 'detailPage'
    ,count: 50
    ,theme: '#627794'
    ,layout: ['page', 'next']
  });
  //搜索页——时间
  var pushDate = new Date()
  ,pushDateYear = pushDate.getFullYear()
  ,pushDateMon = pushDate.getMonth() + 1
  ,pushDateDay = pushDate.getDate()
  ,pushDateHour = pushDate.getHours()
  ,pushDateMin = pushDate.getMinutes()
 // $(".news-search").find(".pushTime").html(pushDateYear + '-' + pushDateMon + '-' + pushDateDay + ' ' + pushDateHour + ':' + pushDateMin)

  //登录页——弹框
  $(".news-login").find("#getCode").on('click', function(){
    layer.msg('验证码已发送');
  });
  form.on('submit(newsLogin)', function(data){
    window.location.href = "user.html";
  });
  //个人中心——分页——评论
  laypage.render({
    elem: 'userComPage'
    ,count: 50
    ,theme: '#627794'
    ,layout: ['page', 'next']
  });
  //个人中心——分页——文章
  laypage.render({
    elem: 'userArtPage'
    ,count: 50
    ,theme: '#627794'
    ,layout: ['page', 'next']
  });
  //个人中心——发表新闻
  $(".news-user").find("#pushNews").on('click', function(){
    layer.open({
      type: 2
      ,title: '发布文章'
      ,area: ['720px', '660px']
      ,offset: '170px'
      ,shade: 0.7
      ,skin: 'news-pushCont'
      ,content: 'iframe.html'
      ,success: function(layero, index){
        window['layui-layer-iframe'+ index].layui.form.on('submit(publishNews)', function(data){
          layer.close(index);
        });  
      }
    });
  });
  //个人中心——删除文章
  var userArt =  $(".news-user").children(".userCont").children(".layui-tab-content").find(".article");
  $(".news-user").find("#upDel").on('click', function(){
    $(".news-user").find("#batchDel").toggle();
    $(".news-user").find("#cancelDel").toggle();
    userArt.children("li").each(function(){
      $(this).children(".layui-form-checkbox").toggle();
    });
  });
  $(".news-user").find("#cancelDel").on('click', function(){
    $(".news-user").find("#batchDel").toggle();
    $(".news-user").find("#cancelDel").toggle();
    userArt.children("li").each(function(){
      $(this).children("input")[0].checked = false;
      $(this).children(".layui-form-checkbox").hide();
    });
    form.render('checkbox');
  });
  $(".news-user").find("#batchDel").on('click', function(){
    userArt.children("li").each(function(){
      if($(this).children(".layui-form-checkbox").hasClass("layui-form-checked")){
        $(this).remove();
      }
    });
    userArt.children("li").each(function(index){
      $(this).removeClass("even");
      if(index%2 != 0){
        $(this).addClass("even");
      }
    });
  });
  exports('news', {}); 
})